//
//  RegistVC.m
//  YaoHeAPP
//
//  Created by mac on 15/11/20.
//  Copyright (c) 2015年 mac. All rights reserved.
//

#import "RegistVC.h"
#import "Masonry.h"
#import "LoginVC.h"
#import "WebVC.h"
#import "Controller.h"
#import "Define.h"
#import "RegistSuccess.h"
#import "MKNetworkEngine.h"
#import "Define.h"
#import "IssueSuccess.h"
#import "YunBaService.h"
#import "MBProgressHUD.h"

@interface RegistVC ()


@end

@implementation RegistVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"RegistVC"];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"RegistVC"];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    width=self.view.frame.size.width;
    height=self.view.frame.size.height;
    
    textArray=[[NSMutableArray alloc]init];
    
    self.view.backgroundColor=bgVCcolor;
    //加一个导航条
    UIView*navcBar=[[UIView alloc]init];
    navcBar.backgroundColor=[UIColor colorWithRed:90.f/255.f green:191.f/255.f blue:219.f/255.f alpha:1];
    [self.view addSubview:navcBar];
    [self.view bringSubviewToFront:navcBar];
    [navcBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);   make.left.offset(0);
        make.height.offset(60);  make.right.offset(0);
    }];
    //导航条标题
    UILabel*titleLabel=[[UILabel alloc]init];
    titleLabel.text=@"快速注册";
    titleLabel.font=Font(17);
    titleLabel.textAlignment=NSTextAlignmentCenter;
    titleLabel.textColor=[UIColor whiteColor];
    [navcBar addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(25);
        make.left.offset(width/2-50);
        make.width.offset(100);
        make.height.offset(30);
    }];
    
    //返回按钮
    UIButton*leftButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backLogin) forControlEvents:UIControlEventTouchUpInside];
    [navcBar addSubview:leftButton];
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(6);
        make.width.offset(24);
        make.height.offset(22);
        make.bottom.offset(-12);
    }];
    
    //右侧登录按钮
    UIButton*rightButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setTitle:@"登录" forState:UIControlStateNormal];
    rightButton.titleLabel.font=Font(14);
    [rightButton addTarget:self action:@selector(backLogin) forControlEvents:UIControlEventTouchUpInside];
    [navcBar addSubview:rightButton];
    [rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-6);
        make.width.offset(60);
        make.height.offset(28);
        make.bottom.offset(-6);
    }];

    //一个大的视图包含输入框所有内容
    bigView=[[UIView alloc]init];
    bigView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:bigView];
    [bigView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(70);
        make.left.offset(0);
        make.right.offset(0);
        make.height.offset(300);
    }];
   
    labelArray=[[NSArray alloc]initWithObjects:@"手机号:",@"设置密码:",@"确认密码:",@"推荐人手机号:",nil];
    placeArray=[[NSArray alloc]initWithObjects:@"请输入手机号",@"请输入6~20位数字或字母",@"请再次输入一次密码",@"非必填",nil];
    
    for (NSInteger i=0; i<4 ;i++)
    {
        backView=[[UIView alloc]init];
        backView.backgroundColor=[UIColor whiteColor];
        [bigView addSubview:backView];
        [backView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(i*51);
            make.left.offset(0);
            make.right.offset(0);
            make.height.offset(50);
        }];

        //必填的内容前的星星图片
        UIImageView*startImage=[[UIImageView alloc]init];
        if (i==3)
        {
            startImage.image=nil;
        }
        else{
        startImage.image=[UIImage imageNamed:@"bi_tian"];
        }
        [backView addSubview:startImage];
        [startImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(17);
            make.left.offset(5);
            make.height.offset(16);
            make.width.offset(17);
        }];
        
        //提示标签
        UILabel*phone=[[UILabel alloc]init];
        phone.font=[UIFont systemFontOfSize:15];
        phone.text=labelArray[i];
        [backView addSubview:phone];
        [phone mas_makeConstraints:^(MASConstraintMaker*make) {
            make.left.offset(28);
            make.top.offset(6);
            make.bottom.offset(-6);
            make.width.offset([self getTextwidthWithString:labelArray[i]]);
        }];
        
        //手机号输入框
        phoneText=[[UITextField alloc]init];
        phoneText.font=[UIFont systemFontOfSize:14];
        phoneText.placeholder=placeArray[i];
        phoneText.clearButtonMode=UITextFieldViewModeWhileEditing;
        phoneText.borderStyle=UITextBorderStyleNone;
        phoneText.tag=100+i;
        phoneText.delegate=self;
        if (i==1||i==2) {
            phoneText.secureTextEntry=YES;
        }
        [phoneText addTarget:self action:@selector(keyboardDissmiss) forControlEvents:UIControlEventEditingDidEndOnExit];
        [backView addSubview:phoneText];
        [phoneText mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(phone.mas_right).offset(2);
            make.right.offset(-6);
            make.top.offset(5);
            make.bottom.offset(-5);
        }];
    }
    
    //同意协议选择框
    selectBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [selectBtn setBackgroundImage:[UIImage imageNamed:@"okandborder"] forState:UIControlStateNormal];
    selectBtn.selected=YES;
    [selectBtn addTarget:self action:@selector(selectDelegate) forControlEvents:UIControlEventTouchUpInside];
    [bigView addSubview:selectBtn];
    [selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(215);
        make.left.offset(12);
        make.height.offset(15);
        make.width.offset(15);
    }];
    
    //我已阅读并同意协议的label
    UILabel*delegateLab=[[UILabel alloc]init];
//    delegateLab.backgroundColor=[UIColor yellowColor];
    delegateLab.font=[UIFont systemFontOfSize:12];
    delegateLab.text=@"我已阅读并同意协议";
    delegateLab.textColor=[UIColor grayColor];
    [bigView addSubview:delegateLab];
    [delegateLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(215);
        make.left.equalTo(selectBtn.mas_right).offset(3);
        make.height.offset(15);
        make.width.offset(110);
    }];
    
    //吆喝协议
    UIButton*xieyi=[UIButton buttonWithType:UIButtonTypeCustom];
    xieyi.titleLabel.font=[UIFont systemFontOfSize:13];
    [xieyi setTitle:@"《吆喝协议》" forState:UIControlStateNormal];
    [xieyi setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [xieyi addTarget:self action:@selector(yaoheDeledate) forControlEvents:UIControlEventTouchUpInside];
    [bigView addSubview:xieyi];
    [xieyi mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(215);
        make.left.equalTo(delegateLab.mas_right).offset(1);
        make.height.offset(15);
        make.width.offset(78);
    }];
    
    //立即注册按钮
    UIButton*registBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [registBtn setTitle:@"快速注册" forState:UIControlStateNormal];
    UIImage*loginOldImg=[UIImage imageNamed:@"loginbutton"];
    UIImage*loginNewImg=[loginOldImg stretchableImageWithLeftCapWidth:15 topCapHeight:0];
    [registBtn setBackgroundImage:loginNewImg forState:UIControlStateNormal];
    [registBtn addTarget:self action:@selector(registBtn) forControlEvents:UIControlEventTouchUpInside];
    [bigView addSubview:registBtn];
    [registBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(240);
        make.left.offset(50);
        make.right.offset(-50);
        make.height.offset(40);
    }];
  
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    return YES;
}

//快速注册按钮
-(void)registBtn
{
    [MobClick event:@"fastRegistration"];
    
   if (selectBtn.selected==NO)
    {
        UIAlertView*alertView=[[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"亲，你需要同意我们的协议才能进行注册，谢谢合作。" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
        return;
    }
    //同意后
     UITextField*phoneTag=(UITextField*)[self.view viewWithTag:100];
     UITextField*passwordTag=(UITextField*)[self.view viewWithTag:101];
     UITextField*paswAginTag=(UITextField*)[self.view viewWithTag:102];
     UITextField*reconnendTag=(UITextField*)[self.view viewWithTag:103];
    
    //判断用户输入的内容

    if (phoneTag.text.length!=11)
    {
        ALERTSHOW(@"手机号格式不正确");
        return;
    }
    if (passwordTag.text.length<6||passwordTag.text.length>20)
    {
        ALERTSHOW(@"密码格式不正确，请重新输入");
        return;
    }
    if (![passwordTag.text isEqualToString:paswAginTag.text])
    {
        ALERTSHOW(@"两次输入的密码不一致，请重新输入");
        return;
    }

    // TODO 使用申请的极速验证应用公钥   085ca907573441ac9db974961d1df9bc
//                                  231d5c687779319603f591cbc9201d75
    // TODO 使用申请的极速验证应用公钥
    static NSString * const GT_captcha_id =  @"231d5c687779319603f591cbc9201d75";
    
    GTManager *manager = [GTManager sharedGTManger];
    
    //检测极速验证服务器是否畅通（可添加请求提示）
    if ([manager serverStatusWithCaptcha_id:GT_captcha_id]) {
        [manager openGTViewAddFinishHandler:^(NSString *code, NSDictionary *result, NSString *message) {
            if ([code isEqualToString:@"1"]) {
                //NSString*jsonString=[NSString string];
                //判断推荐人手机号码是否填了
                if (reconnendTag.text.length == 0)
                {
                NSDictionary*dic=@{@"MOBILE":phoneTag.text,@"PASSWORD":passwordTag.text,@"challenge":result[@"geetest_challenge"],@"validstr":result[@"geetest_validate"],@"seccode":result[@"geetest_seccode"],@"BRAND":@"apple"};
                    
                    [Controller requestWithURL:REGISTAPI jsondic:dic finishBlock:^(ClassData*data) {
                        if ([data.number integerValue]==0)
                        {
                            NSString *userid=[NSString stringWithFormat:@"%@",data.data[@"USER_ID"]];
                            
                            NSString *publisher=[NSString stringWithFormat:@"%@",data.data[@"SESSION_ID"]];
                            
                            [[NSUserDefaults standardUserDefaults] setObject:userid forKey:USERID];
                            [[NSUserDefaults standardUserDefaults] setObject:publisher forKey:PUBLISHER];
                            
                            
                            [YunBaService subscribe:userid resultBlock:^(BOOL succ, NSError *error){
                                if (succ) {
                                } else {
                                }
                            }];
                            
                            [[NSUserDefaults standardUserDefaults]setObject:@"成功" forKey:@"状态"];
                            
                            NSDictionary*dic=data.data;
                            IssueSuccess*score=[[IssueSuccess alloc]initWithDic:dic];
                            UIAlertView*alertView=[[UIAlertView alloc]initWithTitle:@"温馨提示" message:score.userScoreIncMsg delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil];
                            alertView.tag=200;
                            [alertView show];
                        }
                        else
                        {
                            ALERTSHOW(data.message);
                        }
                    }];
                    
                }
                else
                {
                    if (reconnendTag.text.length!=11)
                    {
                        ALERTSHOW(@"手机号格式不正确");
                        return;
                    }
                    if ([phoneTag.text isEqualToString:reconnendTag.text])
                    {
                        ALERTSHOW(@"推荐人手机号不能与自己的手机号重复,请重新输入");
                        return;
                    }
                NSDictionary*dic=@{@"MOBILE":phoneTag.text,@"PASSWORD":passwordTag.text,@"challenge":result[@"geetest_challenge"],@"validstr":result[@"geetest_validate"],@"seccode":result[@"geetest_seccode"],@"RECOMMEND_MOBILE":reconnendTag.text,@"BRAND":@"apple"};
                    [Controller requestWithURL:REGISTAPI jsondic:dic finishBlock:^(ClassData*data) {
                        if ([data.number integerValue]==0)
                        {
                            NSString *userid=[NSString stringWithFormat:@"%@",data.data[@"USER_ID"]];
                            
                            NSString *publisher=[NSString stringWithFormat:@"%@",data.data[@"SESSION_ID"]];
                            
                            [[NSUserDefaults standardUserDefaults] setObject:userid forKey:USERID];
                            [[NSUserDefaults standardUserDefaults] setObject:publisher forKey:PUBLISHER];
                            
                            [YunBaService subscribe:userid resultBlock:^(BOOL succ, NSError *error){
                                if (succ) {
                                } else {

                                }
                            }];
                            
                            [[NSUserDefaults standardUserDefaults]setObject:@"成功" forKey:@"状态"];
                            
                            NSDictionary*dic=data.data;
                            IssueSuccess*score=[[IssueSuccess alloc]initWithDic:dic];
                            UIAlertView*alertView=[[UIAlertView alloc]initWithTitle:@"温馨提示" message:score.userScoreIncMsg delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil];
                            alertView.tag=201;
                            [alertView show];
                            
                        }
                        else
                        {
                            ALERTSHOW(data.message);
                        }
                    }];
                    
                }
            }
            else {
                [manager closeGTViewIfIsOpen];
            }

        } closeHandler:^{
            
        }];
        
    }
}

//吆喝协议按钮
-(void)yaoheDeledate
{
    WebVC*webVC=[WebVC new];
    webVC.titleTxt=@"吆喝协议";
    webVC.urlString=[NSString stringWithFormat:@"%@/WEB/mobile/register_agreement.aspx",BESTHOST];
    [self.navigationController pushViewController:webVC animated:YES];
}

//打勾框框、同意协议框
-(void)selectDelegate
{
    if (selectBtn.selected==YES)
    {
        [selectBtn setBackgroundImage:[UIImage imageNamed:@"Agreed"] forState:UIControlStateNormal];
        selectBtn.selected=NO;
        return;
    }
    if (selectBtn.selected==NO) {
        [selectBtn setBackgroundImage:[UIImage imageNamed:@"okandborder"] forState:UIControlStateNormal];
        selectBtn.selected=YES;
        return;
    }

}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==200||alertView.tag==201) {
        UITextField*phoneTag=(UITextField*)[self.view viewWithTag:100];
        RegistSuccess*registsuVC=[RegistSuccess new];
        registsuVC.numberPhone=phoneTag.text;
        [self.navigationController pushViewController:registsuVC animated:YES];
    }
}


//计算文字宽度（设置label的高度）
-(NSInteger)getTextwidthWithString:(NSString *)string
{
    CGRect rect = [string boundingRectWithSize:CGSizeMake(MAXFLOAT,38) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15]} context:nil];
    return rect.size.width+8;
}

//返回登录界面
-(void)backLogin
{
    [self.navigationController popViewControllerAnimated:YES];
}


//键盘弹下
-(void)keyboardDissmiss
{
    return;
}
//键盘弹下
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

-(void)keyBoardFrameChange:(NSNotification *)notification
{
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
#endif
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_3_2
        NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
#else
        NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey];
#endif
        CGRect keyboardBounds;
        [keyboardBoundsValue getValue:&keyboardBounds];
        
        NSInteger offset =self.view.frame.size.height-keyboardBounds.origin.y;
        CGRect listFrame;
        if (offset==252) {
           listFrame = CGRectMake(0, -50, self.view.frame.size.width,self.view.frame.size.height);
        }else{
        
           listFrame = CGRectMake(0,0, self.view.frame.size.width,self.view.frame.size.height);
        }
        [UIView beginAnimations:@"anim" context:NULL];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationDuration:0.2];
        //处理移动事件，将各视图设置最终要达到的状态
        self.view.frame=listFrame;
        [UIView commitAnimations];
    }
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
   
//    txtFrame=textField.frame;
    
}

@end
